package com.kasax.skin;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kasax.skin.utils.FileUtils;
import com.kasax.skin.utils.LogUtils;
import com.kasax.skin.utils.permissions.PermissionUtils;

import java.io.File;
import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {

    private PermsssionCallbackImpl callback;
    private Context mContext;
    private File targetFile;

    private ImageView mImageView;
    private TextView mTextView;

    private class PermsssionCallbackImpl implements PermissionUtils.HandleCallback {

        @Override
        public void skipPermissionRequest() {
            if (!targetFile.exists()) {
                FileUtils.copySkinToSdcard(mContext, "SkinDemo-pack.apk", targetFile);
            }
        }

        @Override
        public void noPermission() {

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;

        mImageView = findViewById(R.id.image_view);
        mTextView = findViewById(R.id.text_view);
        PermissionUtils.injectContext(this);
        callback = new PermsssionCallbackImpl();

        targetFile = new File(getExternalFilesDir(null), "SkinDemo-pack.apk");
        PermissionUtils.requestSdcardPermission(callback);

        loadDefaultSink();
    }

    private void loadDefaultSink() {
        try (AssetManager assetManager = AssetManager.class.newInstance()) {
            // 反射调用addAssetPath
            Method addAssetPathMethod = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
            // 获取当前apk在手机中的路径
            String path = getApplicationContext().getPackageResourcePath();
            LogUtils.i(getClass(), "loadDefaultSink path: " + path);
            /// 反射执行方法
            addAssetPathMethod.invoke(assetManager, path);

            // 创建自己的Resources
            Resources resources = new Resources(assetManager, createDisplayMetrics(), createConfiguration());
            // 通过id来获取图片
            Drawable drawable = resources.getDrawable(R.drawable.ic_launcher_background, null);
            if (resources != null) {
                mImageView.setImageDrawable(drawable);
            }
        } catch (Exception e) {
            LogUtils.e(getClass(), e);
        }

    }

    private Configuration createConfiguration() {
        return getResources().getConfiguration();
    }

    private DisplayMetrics createDisplayMetrics() {
        return getResources().getDisplayMetrics();
    }

    public void btnClick(View view) {
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            // 反射调用addAssetPath
            Method addAssetPathMethod = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
            addAssetPathMethod.setAccessible(true);
            // 获取当前apk在手机中的路径
            String path = targetFile.getPath();
            LogUtils.i(getClass(), "btnClick path: " + path);
            /// 反射执行方法
            addAssetPathMethod.invoke(assetManager, path);

            // 创建自己的Resources
            Resources resources = new Resources(assetManager, createDisplayMetrics(), createConfiguration());
            // int drawableId = resources.getIdentifier("shark", "drawable", "com.skin.skin_pack_making");
            String packName = getPkgName(path);
            LogUtils.i(getClass(), "pkgName: " + packName);
            /// 加载drawable
            int drawableId = resources.getIdentifier("shark", "drawable", packName);
            LogUtils.i(getClass(), "drawableId: " + drawableId);
            // 加载string
            int stringId = resources.getIdentifier("hello_skin", "string", packName);
            LogUtils.i(getClass(), "stringId: " + stringId);
            // 加载color
            int colorId = resources.getIdentifier("global_background", "color", packName);
            LogUtils.i(getClass(), "colorId: " + colorId);

            mImageView.setImageDrawable(resources.getDrawable(drawableId, null));
            mTextView.setText(resources.getString(stringId));
            mTextView.setBackgroundColor(resources.getColor(colorId, null));
        } catch (Exception e) {
            LogUtils.e(getClass(), e);
        }
    }

    /**
     * 获取安装apk包名
     *
     * @param path
     * @return
     */
    private String getPkgName(String path) {
        PackageInfo info = getPackageManager().getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo applicationInfo = info.applicationInfo;
            return applicationInfo.packageName;
        }
        return null;
    }

    public void resetClick(View view) {
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAssetPathMethod = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
//            addAssetPathMethod.setAccessible(true);
            // 获取当前apk在手机中的路径
            String path = getApplicationContext().getPackageResourcePath();
            LogUtils.i(getClass(), "resetClick path: " + path);
            addAssetPathMethod.invoke(assetManager, path);

            Resources resources = new Resources(assetManager, createDisplayMetrics(), createConfiguration());
            int drawableId = resources.getIdentifier("shark", "drawable", "com.kasax.skin");
            Toast.makeText(this, drawableId + "", Toast.LENGTH_SHORT).show();
            mImageView.setImageDrawable(resources.getDrawable(drawableId, null));
        } catch (Exception e) {
            LogUtils.e(getClass(), e);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        PermissionUtils.handleIntentPermissionRequestResult(requestCode, resultCode, callback);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.handleOnRequestPermissionsResult(requestCode, permissions, false, callback);
    }
}